﻿using System.Collections.Generic;
using VisionarySystems.TimeRegi.Database;
using VisionarySystems.TimeRegi.Model;
using VisionarySystems.TimeRegi.Model.TimePeriods;

namespace VisionarySystems.TimeRegi.Controller
{
	public interface ITimeRegistrationController
	{
		int DeleteTimePeriode(TimePeriodeID TimePeriodeID);
		void ApplicationClosing();
		void ShutDown();
		void StartPause();
		int AssembleTimeslots(TimePeriodeID TimePeriodeID);
		void UpdateTimeSlot(TimeSlot EditedTimeSlot);
	}

	public class TimeRegistrationController : ITimeRegistrationController
	{
		#region private members

		private readonly TimeRegistrationViewModel m_ViewModel;

		#endregion

		#region Ctor
		
		public TimeRegistrationController(TimeRegistrationViewModel ViewModel)
		{
			m_ViewModel = ViewModel;
		}

		#endregion

		#region public methods

		public int DeleteTimePeriode(TimePeriodeID TimePeriodeID)
		{
			int result = 0;
			ITimePeriode periode = m_ViewModel.GetTimePeriode(TimePeriodeID);
			if (periode != null)
				result = m_ViewModel.DeleteTimePeriode(periode);
			return result;
		}

		public void ApplicationClosing()
		{
			m_ViewModel.ApplicationClosing();
		}

		public void ShutDown()
		{
			m_ViewModel.ShutDown();
		}

		public void StartPause()
		{
			m_ViewModel.StartPause();
		}

		public int AssembleTimeslots(TimePeriodeID TimePeriodeID)
		{
			int result;
			//m_UpdateInProgress = true;
			try
			{
				ITimePeriode periode = m_ViewModel.GetTimePeriode(TimePeriodeID);
				List<int> removedIndexes;
				List<TimeSlot> newTimeSlots;
				if (periode != null && periode.AssembleTimeslots(out newTimeSlots, out removedIndexes))
				{
					result = removedIndexes.Count;
					foreach (int idx in removedIndexes)
						DataLayer.DeleteTimeSlot(idx);
					foreach (TimeSlot slot in newTimeSlots)
						m_ViewModel.SaveTimeSlot(slot);
				}
				else
					result = -1;
			}
			finally
			{
				//m_UpdateInProgress = false;
			}
			//NotifyObservers();
			return result;
		}

		public void UpdateTimeSlot(TimeSlot EditedTimeSlot)
		{
			m_ViewModel.UpdateTimeSlot(EditedTimeSlot);
		}

		#endregion

	}
}